package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import model.ChartGenerator;

public class RatingPane extends JPanel implements Observer {

	private static final long serialVersionUID = 1L;

	JTextArea area = new JTextArea();
	ChartGenerator chart;

	public RatingPane(ChartGenerator chart) {
		setLayout(new BorderLayout());
		this.chart = chart;
		chart.addObserver(this);

		setLayout(new BorderLayout());

		area.setEditable(false);
		area.setBackground(Color.WHITE);

		add(area, BorderLayout.CENTER);
		JScrollPane scrollPane = new JScrollPane(area);
		add(scrollPane);

	}

	/**
	 * riceve e formatta le classifiche; sì, è un po' SRP
	 */
	@Override
	public void update(Observable arg0, Object arg1) {

		if (chart.getTeamStatus()) {

			area.setText("");
			Set<Integer> keys = chart.getTeamChart().keySet();
			// Set<Integer> orderedkeys = new TreeSet<Integer>();
			// orderedkeys.addAll(keys);

			String[] teamChart = new String[chart.getTeamChart().size()];
			int i = chart.getTeamChart().size() - 1;

			for (Integer key : keys) {
				String value = chart.getTeamChart().get(key);

				teamChart[i] = ((i + 1) + " " + value + " " + key + "\n")
						.toString();

				i--;
			}

			for (int j = 0; j < teamChart.length; j++) {
				area.append(teamChart[j]);

			}

		}

		if (chart.getFacStatus()) {

			area.setText("");

			Set<Integer> keys = chart.getFacChart().keySet();
			// Set<Integer> orderedkeys = new TreeSet<Integer>();
			// orderedkeys.addAll(keys);

			String[] facChart = new String[chart.getFacChart().size()];
			int i = facChart.length - 1;

			for (Integer key : keys) {
				String value = chart.getFacChart().get(key);

				facChart[i] = ((i + 1) + " " + value + " " + key + "\n")
						.toString();

				// format("%d %s %d",i+1, value, key);

				i--;

			}

			for (int j = 0; j < facChart.length; j++) {
				area.append(facChart[j]);

			}

		}

	}

}
